﻿
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

public partial class RatateSpeedSystem_IJobEntityBatch : SystemBase
{
    private EntityQuery _entityQuery;

    protected override void OnCreate()
    {
        _entityQuery = GetEntityQuery(typeof(Rotation), ComponentType.ReadOnly<RotateSpeed_IJobEntityBatch>());
    }

    [BurstCompatible]
    public struct RotateSpeedJob : IJobEntityBatch
    {
        public float DeltaTime;

        public ComponentTypeHandle<Rotation> RotationTypeHandle;
        
        [ReadOnly]public ComponentTypeHandle<RotateSpeed_IJobEntityBatch> RotateSpeedIJobEntityBatchHandle;
        
        public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
        {
            var chunkRotations = batchInChunk.GetNativeArray(RotationTypeHandle);
            var chunkSpeeds = batchInChunk.GetNativeArray(RotateSpeedIJobEntityBatchHandle);
            for (int i = 0; i < batchInChunk.Count; i++)
            {
                var rotation = chunkRotations[i];
                var speed = chunkSpeeds[i];
                chunkRotations[i] = new Rotation()
                {
                    Value = math.mul(math.normalize(rotation.Value),
                        quaternion.AxisAngle(math.up(), speed.RadiansPerSecond * DeltaTime))
                };
            }
        }
    }

    protected override void OnUpdate()
    {
        // Explicitly declare:
        // - Read-Write access to Rotation
        // - Read-Only access to RotationSpeed_IJobChunk
        var rotationType = GetComponentTypeHandle<Rotation>();
        var rotationSpeedType = GetComponentTypeHandle<RotateSpeed_IJobEntityBatch>(true);

        var job = new RotateSpeedJob()
        {
            RotationTypeHandle = rotationType,
            RotateSpeedIJobEntityBatchHandle = rotationSpeedType,
            DeltaTime = Time.DeltaTime
        };

        Dependency = job.ScheduleParallel(_entityQuery, Dependency);
    }
}